package com.xncoding.freemarker.ex;

import com.xncoding.freemarker.base.*;
import com.xncoding.freemarker.model.response.ErrorCode;
import com.xncoding.freemarker.model.response.RestResponse;
import com.xncoding.freemarker.model.response.RestResponses;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.ConversionNotSupportedException;
import org.springframework.beans.TypeMismatchException;
import org.springframework.context.support.DefaultMessageSourceResolvable;
import org.springframework.http.HttpStatus;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.http.converter.HttpMessageNotWritableException;
import org.springframework.validation.BindException;
import org.springframework.web.HttpMediaTypeNotAcceptableException;
import org.springframework.web.HttpMediaTypeNotSupportedException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingPathVariableException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.ServletRequestBindingException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.context.request.async.AsyncRequestTimeoutException;
import org.springframework.web.multipart.support.MissingServletRequestPartException;
import org.springframework.web.servlet.NoHandlerFoundException;

import javax.servlet.http.HttpServletRequest;
import javax.validation.ConstraintViolationException;
import java.util.stream.Collectors;
/**
 * idcoed:2025021116
 */
/**
 * 全局异常处理，捕获所有Controller中抛出的异常。
 *
 * @author wgb
 * @date 2019/7/19
 */
@Slf4j
@ControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 参数校验异常
     * @param ex 校验异常
     * @return ErrorResponse
     */
    @ExceptionHandler({BindException.class, MethodArgumentNotValidException.class})
    @ResponseStatus(HttpStatus.FORBIDDEN)
    public ErrorResponse validExceptionHandler(Exception ex , HttpServletRequest request) {
        String errMsg = null;
        if (ex instanceof BindException) {
            errMsg = ((BindException) ex).getBindingResult().getFieldErrors()
                    .stream().map(error -> error.getField() + ":" +error.getDefaultMessage())
                    .collect(Collectors.joining(";"));
        } else if (ex instanceof MethodArgumentNotValidException) {
            errMsg = ((MethodArgumentNotValidException) ex).getBindingResult().getFieldErrors()
                    .stream().map(error -> error.getField() + ":" + error.getDefaultMessage())
                    .collect(Collectors.joining(";"));
        }
        log.error(errMsg);
        return this.handleBusinessException(new CommonException(CommonErrorCode.BAD_REQUEST,errMsg),request);
    }

    /**
     * 业务异常
     * @param ex 业务异常
     * @param request 请求
     * @return ErrorResponse
     */
    @ExceptionHandler(BaseException.class)
    @ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR)
    public ErrorResponse handleBusinessException(BaseException ex, HttpServletRequest request) {
        log.error("业务异常：url:{}，参数：{}", request.getRequestURI(), request.getQueryString(), ex);
        return new ErrorResponse(ex, request.getRequestURI());
    }

    /**
     * 最后兜底的异常
     * @param ex 异常
     */
/*    @ExceptionHandler({Exception.class})
    @ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR)
    public ErrorResponse exceptionHandler(Exception ex,HttpServletRequest request) {
        log.error("最后兜底的异常：url:{}，参数：{}", request.getRequestURI(), request.getQueryString(), ex);
        return this.handleBusinessException(new CommonException(CommonErrorCode.INTERNAL_SERVER_ERROR,ex.getMessage()),request);
    }*/


    /**
     * 处理自定义异常，其他未处理的异常，按系统异常处理
     */
/*    @ExceptionHandler(Exception.class)
    @ResponseBody
    public RestResponse<String> exceptionHandler(Exception e) {
        return RestResponses.newFailResponse(ErrorCode.SYSTEM_ERROR, e.getMessage());
    }*/


    /**
     * 处理Get请求中 使用@Valid 验证路径中请求实体校验失败后抛出的异常
     */
/*    @ExceptionHandler(BindException.class)
    @ResponseBody
    public R BindExceptionHandler(BindException e) {
        String message = e.getBindingResult().getAllErrors().stream().map(DefaultMessageSourceResolvable::getDefaultMessage).collect(Collectors.joining());
        return R.failure().code(ResultCodeEnum.PARAM_ERROR.getCode()).message(message);
    }*/
    /**
     * 通用异常处理方法
     **/
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public R error(Exception e) {
        e.printStackTrace();
        return R.setResult(ResultCodeEnum.INTERNAL_SERVER_ERROR);
    }

    /**
     * 指定异常处理方法
     **/
    @ExceptionHandler(NullPointerException.class)
    @ResponseBody
    public R error(NullPointerException e) {
        e.printStackTrace();
        return R.setResult(ResultCodeEnum.NULL_POINT);
    }
    /**
     * 处理Get请求中  使用@Validated 验证路径中 单个参数请求失败抛出异常
     * @param e
     * @return
     */
    @ExceptionHandler(ConstraintViolationException.class)
    public R ConstraintViolationExceptionHandler(ConstraintViolationException e) {
//        String message = e.getConstraintViolations().stream().map(ConstraintViolation::getMessage).collect(Collectors.joining());
        String message = "";
        return R.failure().code(ResultCodeEnum.PARAM_ERROR.getCode()).message(message);
    }



    /**
     * Controller上一层相关异常
     *
     * @param e 异常
     * @return 异常结果
     */
    @ExceptionHandler({
            NoHandlerFoundException.class,
            HttpRequestMethodNotSupportedException.class,
            HttpMediaTypeNotSupportedException.class,
            MissingPathVariableException.class,
            MissingServletRequestParameterException.class,
            TypeMismatchException.class,
            HttpMessageNotReadableException.class,
            HttpMessageNotWritableException.class,
            // BindException.class,
            // MethodArgumentNotValidException.class
            HttpMediaTypeNotAcceptableException.class,
            ServletRequestBindingException.class,
            ConversionNotSupportedException.class,
            MissingServletRequestPartException.class,
            AsyncRequestTimeoutException.class
    })
    @ResponseBody
    public R error00(Exception e) {
        return R.failure().message(e.getMessage()).code(ResultCodeEnum.PARAM_ERROR.getCode());
    }


}
